<template>
  <div class="login-container">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item prop="username">
        <el-input
          v-model.trim="form.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model.trim="form.password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { ElFormType } from '@/global'
// import useStore from 'element-plus/lib/el-table/src/store'
import { defineComponent, reactive, ref, toRefs } from 'vue'
import { useStore } from '@/store'
import { UserActionTypes } from '@/store/modules/user'
import { ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
export default defineComponent({
  name: 'Login',
  setup() {
    const store = useStore()
    const router = useRouter()
    const state = reactive({
      loading: false,
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能玩为空',
            trigger: 'blur'
          }
        ]
      }
    })
    const formRef = ref<ElFormType | null>(null)

    const handleSubmit = () => {
      formRef.value?.validate().then(async valid => {
        if (!valid) return
        let loadingInstance = ElLoading.service({
          fullscreen: true,
          text: '数据加载中'
        })
        try {
          const res = await store.dispatch(
            UserActionTypes.ACTION_LOGIN,
            state.form
          )
          console.log(res)
          router.push('/')
        } catch (error) {
          console.log(error)
        }
        loadingInstance.close()
      })
    }

    const refState = toRefs(state)
    return {
      ...refState,
      formRef,
      handleSubmit
    }
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  width: 500px;
  margin: 0 auto;
}
</style>
